﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using spUtils;
using spMapping;
using spData.Common;

namespace demo.Controls
{
    public partial class AttachmentBase : System.Web.UI.UserControl
    {
        #region Property
        public string UrlRoot
        {
            get { return ResolveUrl("~/"); }
        }
        public string FileClass
        {
            get{ return ViewState["FileClass"] == null ? "" : (string)ViewState["FileClass"]; }
            set{ ViewState["FileClass"] = value; }
        }
        public bool AllowUpload
        {
            get { return ViewState["AllowUpload"] == null ? true : (bool)ViewState["AllowUpload"]; }
            set { ViewState["AllowUpload"] = value; }
        }
        public bool AllowDelete
        {
            get { return ViewState["AllowDelete"] == null ? true : (bool)ViewState["AllowDelete"]; }
            set { ViewState["AllowDelete"] = value; }
        }
        public string Process
        {
            get { return ViewState["Process"] == null ? "" : (string)ViewState["Process"]; }
            set { ViewState["Process"] = value; }
        }
        public string Step
        {
            get { return ViewState["Step"] == null ? "" : (string)ViewState["Step"]; }
            set { ViewState["Step"] = value; }
        }

        public int Incident
        {
            get { return ViewState["Incident"] == null ? 0 : (int)ViewState["Incident"]; }
            set { ViewState["Incident"] = value; }
        }
        public int Max
        {
            get{ return ViewState["Max"] == null ? 999 : (int)ViewState["Max"]; }
            set{ ViewState["Max"] = value; }
        }

        public string IsShow { get { return AllowUpload && this.rep_Attachment.Items.Count < Max ? "" : "display:none;"; } }
        public string FirstFilePath
        {
            get{ return ViewState["FirstFilePath"] == null ? "" : (string)ViewState["FirstFilePath"]; }
            set { ViewState["FirstFilePath"] = value; }
        }
        public bool IsHaveAttachment
        {
            get
            {
                return ViewState["IsHaveAttachment"] == null ? false : (bool)ViewState["IsHaveAttachment"];
            }
            set
            {
                ViewState["IsHaveAttachment"] = value;
            }
        }
        #endregion

        #region Event Load
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                Bind();
            }
        }
        #endregion

        #region Event ItemCommand
        protected void rep_Attachment_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Footer)
            {
                //文件上传
                if (e.CommandName == "Upload")
                {
                    RepeaterItem rep = (rep_Attachment.Controls[rep_Attachment.Controls.Count - 1]) as RepeaterItem;
                    FileUpload fu = (FileUpload)rep.FindControl("File");

                    //如果存在文件的情况
                    if (fu.HasFile)
                    {
                        try
                        {
                            string path = Path.Combine(Utils.CONFIG("FilePath"), Process);
                            string date = System.DateTime.Now.ToString("yyyyMMddHHmmssfff");
                            if (!Directory.Exists(path))
                            {
                                Directory.CreateDirectory(path);
                            }

                            fu.SaveAs(path + @"\" + date + @"~" + fu.FileName);
                            t_Attachment att = new t_Attachment();
                            att.ID           = date;
                            att.Process      = Process;
                            att.Incident     = Incident;
                            att.Step         = Step;
                            //att.UserName     = USER.UserName;
                            //att.UserFullName = USER.UserFullName;
                            //att.Department   = USER.Department;
                            att.Time         = System.DateTime.Now;
                            att.FileName     = fu.FileName;
                            att.FileSize     = string.Format("{0}{1}", ((fu.FileBytes.Length / 1024) <= 0 
                                                                      ? "少于1" : (fu.FileBytes.Length / 1024).ToString()), "K");
                            att.FileClass    = FileClass;
                            att.Status       = 1;
                            ORM.Save(att);

                            Bind();
                        }
                        catch (Exception)
                        {
                        }
                    }
                }

                //文件删除
                if (e.CommandName == "Delete")
                {
                    (t_Attachment.id == e.CommandArgument).Edit<t_Attachment>(o => 
                    {
                        o.Time=System.DateTime.Now;
                        o.Status = 2;
                    });

                    Bind();
                }
            }
        }
        #endregion

        #region Method Bind
        public void Bind()
        {
            Expression exp = new Expression();
            exp &= (t_Attachment.process == Process & t_Attachment.incident == Incident & t_Assessment.process != "" & t_Assessment.step == Step);
            exp &= t_Attachment.fileClass == FileClass;
            exp &= t_Attachment.status == 1;
            List<t_Attachment> list = (List<t_Attachment>)exp.List<t_Attachment>(new Region(0, 100), t_Attachment.time.Asc);

            //加密文件名
            int loc = 0;
            foreach (t_Attachment att in list)
            {
                if (loc == 0)
                {
                    FirstFilePath = list.Count > 0 ? Utils.CONFIG("FilePath") + att.Process + @"\" + list[0].ID + "~" + list[0].FileName : "";
                }
                att.EncryptFileName = Utils.Encrypt(att.Process + @"\" + att.ID + "~" + att.FileName);
                att.FileName = string.IsNullOrEmpty(att.FileName) ? "&nbsp;" : att.FileName;
                att.FileSize = string.IsNullOrEmpty(att.FileSize) ? "&nbsp;" : att.FileSize;
                att.UserFullName = string.IsNullOrEmpty(att.UserFullName) ? "&nbsp;" : att.UserFullName;
            }
            
            IsHaveAttachment = list.Count > 0;
            if (!IsHaveAttachment)
            { 
                t_Attachment blank = new t_Attachment();
                blank.FileName = "没有上传附件.";
                list.Add(blank);
            }

            rep_Attachment.DataSource = list;
            rep_Attachment.DataBind();

            //是否禁用删除
            foreach (RepeaterItem rep in rep_Attachment.Items)
            {
                string UserName = (rep.FindControl("lbl_UserName") as Label).Text;
                ImageButton del = rep.FindControl("img_Del") as ImageButton;
                del.Visible     = AllowDelete && IsHaveAttachment;

                ImageButton icn = rep.FindControl("img_Icon") as ImageButton;
                icn.Visible     = IsHaveAttachment;

                ImageButton viw = rep.FindControl("img_View") as ImageButton;
                viw.Visible     = IsHaveAttachment;
                viw.Attributes["onclick"] = "FileHandler('" + ResolveUrl("~/Workflow/FileHandler.ashx") + "?File=" + viw.CommandArgument + "');";
            }
        }
        #endregion
    }
}
